<template>
  <view class="container">
    <!-- 筛选标签 -->
    <van-sticky>
      <view class="filter-section">
        <van-tabs :value="activeTab" @click="onTabClick">
          <van-tab title="全部" name="all"></van-tab>
          <van-tab title="待支付" name="pending"></van-tab>
          <van-tab title="已支付" name="paid"></van-tab>
          <van-tab title="排队中" name="queuing"></van-tab>
          <van-tab title="已完成" name="completed"></van-tab>
          <van-tab title="已取消" name="cancelled"></van-tab>
        </van-tabs>
      </view>
    </van-sticky>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-section">
      <van-loading size="24px" />
      <text class="loading-text">正在加载挂号记录...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="error-section">
      <van-empty :description="error">
        <van-button type="primary" size="small" @click="fetchAppointments">
          重新加载
        </van-button>
      </van-empty>
    </view>

    <!-- 挂号记录列表 -->
    <view v-else class="appointment-list">
      <view v-if="filteredAppointments.length === 0" class="empty-state">
        <van-empty description="暂无挂号记录">
          <van-button
            type="primary"
            size="small"
            @click="goToAppointment"
          >
            去挂号
          </van-button>
        </van-empty>
      </view>

      <van-card
        v-for="appointment in filteredAppointments"
        :key="appointment.id"
        :title="appointment.doctorName"
        :desc="`${appointment.department} | ${appointment.date} ${appointment.time}`"
        :price="`￥${appointment.fee}`"
      >
        <template #thumb>
          <view class="appointment-icon">
            <van-icon name="calendar-o" color="#07C160" size="24" />
          </view>
        </template>

        <template #tags>
          <van-tag 
            :type="getStatusType(appointment.status)"
            :class="getStatusClass(appointment.status)"
            size="medium"
          >
            {{ appointment.status }}
          </van-tag>
        </template>

        <template #footer>
          <view class="card-actions">
            <van-button
              size="small"
              type="primary"
              plain
              @click="viewDetail(appointment)"
            >
              查看详情
            </van-button>
            
            <!-- 待支付状态可以去支付 -->
            <van-button
              v-if="appointment.status === '待支付'"
              size="small"
              type="primary"
              @click="goToPay(appointment)"
            >
              去支付
            </van-button>
            
            <!-- 已支付状态可以立即到诊，但需要是当天 -->
            <van-button
              v-if="appointment.status === '已支付'"
              size="small"
              :type="canCheckInToday(appointment) ? 'success' : 'default'"
              :disabled="!canCheckInToday(appointment)"
              @click="checkInNow(appointment)"
              :class="canCheckInToday(appointment) ? 'checkin-btn' : 'checkin-btn-disabled'"
            >
              <van-icon name="location" size="12" />
              立即到诊
            </van-button>
            
            <!-- 只有待支付状态可以取消挂号 -->
            <van-button
              v-if="appointment.status === '待支付'"
              size="small"
              type="danger"
              plain
              @click="cancelAppointment(appointment)"
            >
              取消挂号
            </van-button>
            
            <!-- 已完成状态可以评价医生 -->
            <van-button
              v-if="appointment.status === '已完成'"
              size="small"
              @click="rateDoctor(appointment)"
            >
              评价医生
            </van-button>
          </view>
        </template>
      </van-card>
    </view>

    <!-- 详情弹窗 -->
    <van-popup
      v-model:show="showDetail"
      position="bottom"
      :style="{ height: '60%' }"
      closeable
      @close="showDetail = false"
      @click-overlay="showDetail = false"
    >
      <view class="detail-popup" v-if="selectedAppointment">
        <view class="detail-title">挂号详情</view>
        
        <van-cell-group>
          <van-cell title="挂号单号" :value="selectedAppointment.orderNo" />
          <van-cell title="科室" :value="selectedAppointment.department" />
          <van-cell title="医生" :value="selectedAppointment.doctorName" />
          <van-cell title="就诊日期" :value="selectedAppointment.date" />
          <van-cell title="就诊时间" :value="selectedAppointment.time" />
          <van-cell title="挂号费" :value="`￥${selectedAppointment.fee}`" />
          <van-cell title="状态" :value="selectedAppointment.status" />
          <van-cell title="挂号时间" :value="selectedAppointment.createTime" />
          <van-cell title="诊号" :value="selectedAppointment.slotNo?.toString() || '-'" />
        </van-cell-group>

        <view v-if="selectedAppointment.notes" class="detail-notes">
          <van-cell title="备注" :value="selectedAppointment.notes" />
        </view>
      </view>
    </van-popup>
  </view>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getMyAppointments, type MyAppointmentData, putQueue, type PutQueueRequest } from "@/api/appointment";
import { useUserStore } from "@/stores";

interface Appointment {
  id: string;
  orderNo: string;
  department: string;
  doctorName: string;
  staffId: string;
  date: string;
  time: string;
  fee: number;
  status: '待支付' | '已支付' | '已取消' | '排队中' | '已完成';
  createTime: string;
  notes?: string;
  slotNo?: number;
  clnicId?: number;  // 添加 clnicId 字段
}

// 状态映射 - 根据后端实体类定义
const statusMap = {
  0: '待支付',
  1: '已支付',
  2: '已取消', 
  3: '排队中',
  4: '已完成'
} as const;

// 状态码到显示文本的映射
const getStatusText = (statusCode: number): '待支付' | '已支付' | '已取消' | '排队中' | '已完成' => {
  return statusMap[statusCode as keyof typeof statusMap] || '已取消';
};

// 用户状态
const userStore = useUserStore();

const activeTab = ref("all");
const showDetail = ref(false);
const selectedAppointment = ref<Appointment | null>(null);
const loading = ref(false);
const error = ref('');

// 挂号记录数据
const appointments = ref<Appointment[]>([]);

// 转换后端数据格式
const transformAppointmentData = (apiData: MyAppointmentData): Appointment => {
  // 解析日期时间
  const bookedDate = new Date(apiData.bookedAt);
  
  // 使用本地时间格式化日期，避免时区转换问题
  const year = bookedDate.getFullYear();
  const month = String(bookedDate.getMonth() + 1).padStart(2, '0');
  const day = String(bookedDate.getDate()).padStart(2, '0');
  const dateStr = `${year}-${month}-${day}`;
  const timeStr = bookedDate.toLocaleTimeString('zh-CN', { 
    hour12: false, 
    hour: '2-digit', 
    minute: '2-digit' 
  });

  // 添加调试日志查看原始数据
  console.log('原始API数据:', apiData);
  console.log('staffId字段:', apiData.staffId);
  console.log('所有字段:', Object.keys(apiData));

  return {
    id: apiData.id,
    orderNo: apiData.orderId,
    department: apiData.deptName,
    doctorName: apiData.staffName,
    staffId: apiData.staffId || (apiData as any).staff_id || '', // 尝试多种可能的字段名
    date: dateStr,
    time: timeStr,
    fee: 22,
    status: getStatusText(apiData.status),
    createTime: bookedDate.toLocaleString('zh-CN'),
    slotNo: apiData.slotNo,
    clnicId: (apiData as any).clnicId || (apiData as any).clinic_id || undefined
  };
};

// 获取挂号记录
const fetchAppointments = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    // 检查登录状态
    console.log('检查登录状态:', userStore.isLogin);
    console.log('token:', userStore.token);
    console.log('用户信息:', userStore.userInfo);
    
    // if (!userStore.isLogin) {
    //   error.value = '请先登录';
    //   loading.value = false;
    //   return;
    // }
    
    // 从用户store中获取真实用户ID
    const userId = userStore.userInfo.userId || userStore.userData.user.userId;
    console.log("userId",userId)
    if (!userId) {
      error.value = '用户信息异常，请重新登录';
      loading.value = false;
      return;
    }
    
    console.log('获取挂号记录，用户ID:', userId);
    
    const response = await getMyAppointments(userId);
    
    console.log('API响应:', response);
    console.log('完整的后端响应:', JSON.stringify(response, null, 2));
    
    if (response.code === 200) {
      if (Array.isArray(response.data)) {
        appointments.value = response.data.map(transformAppointmentData);
        console.log('转换后的挂号记录:', appointments.value);
      } else {
        console.warn('返回数据格式错误:', response.data);
        appointments.value = [];
      }
    } else {
      error.value = response.msg || '获取挂号记录失败';
      console.error('API返回错误:', response);
    }
  } catch (err) {
    console.error('获取挂号记录异常:', err);
    error.value = '网络错误，请重试';
  } finally {
    loading.value = false;
  }
};

// 修复筛选状态映射，添加缺少的 queuing 状态
const filteredAppointments = computed(() => {
  if (activeTab.value === "all") {
    return appointments.value;
  }
  
  // 修改筛选状态映射 - 添加 queuing 状态
  const filterStatusMap = {
    pending: "待支付",    // 待支付状态
    paid: "已支付",       // 已支付状态  
    queuing: "排队中",    // 添加排队中状态
    completed: "已完成", 
    cancelled: "已取消"
  };
  
  return appointments.value.filter(
    appointment => appointment.status === filterStatusMap[activeTab.value as keyof typeof filterStatusMap]
  );
});

const getStatusType = (status: string) => {
  switch (status) {
    case "待支付":
      return "warning";    // 橙色
    case "已支付":
      return "primary";    // 蓝色
    case "排队中":
      return "success";    // 绿色 - 表示正在进行中
    case "已完成":
      return "default";    // 灰色 - 已完成用灰色
    case "已取消":
      return "danger";     // 红色
    default:
      return "default";
  }
};

const getStatusClass = (status: string) => {
  switch (status) {
    case "排队中":
      return "status-queuing";
    default:
      return "";
  }
};

// 修复 onTabClick 方法
const onTabClick = (tab: any) => {
//   detail:
// index: 2
// name: "paid"
// title: "已支付"
  console.log("切换标签:", tab.detail.name);
  activeTab.value = tab.detail.name;  // 添加这行来更新 activeTab
};

const goToAppointment = () => {
  uni.navigateTo({
    url: "/pages/appointment/department-select"
  });
};

const viewDetail = (appointment: Appointment) => {
  selectedAppointment.value = appointment;
  showDetail.value = true;
};

const cancelAppointment = (appointment: Appointment) => {
  (uni as any).showModal({
    title: "取消挂号",
    content: `确定要取消${appointment.doctorName}的挂号吗？`,
    success: (res: any) => {
      if (res.confirm) {
        // 这里应该调用取消挂号的API
        // 暂时只更新本地状态
        appointment.status = "已取消";
        uni.showToast({
          title: "取消成功",
          icon: "success"
        });
      }
    }
  });
};

const rateDoctor = (appointment: Appointment) => {
  uni.showToast({
    title: "评价功能开发中",
    icon: "none"
  });
};

// 在 script 部分添加去支付方法
const goToPay = (appointment: Appointment) => {
  // 跳转到支付页面
  uni.navigateTo({
    url: `/pages/appointment/payment?orderNo=${appointment.orderNo}&doctorName=${appointment.doctorName}&departmentName=${appointment.department}&date=${appointment.date}&time=${appointment.time}&fee=${appointment.fee}`
  });
};

// 检查是否可以当天到诊
const canCheckInToday = (appointment: Appointment): boolean => {
  const today = new Date();
  const appointmentDate = new Date(appointment.date);
  
  // 比较年月日，忽略时分秒
  const todayStr = today.toISOString().split('T')[0];
  const appointmentStr = appointmentDate.toISOString().split('T')[0];
  
  return todayStr === appointmentStr;
};

// 立即到诊方法 - 添加日期检查
const checkInNow = async (appointment: Appointment) => {
  // 检查是否是当天
  if (!canCheckInToday(appointment)) {
    uni.showToast({
      title: '只能在就诊当天使用立即到诊',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 添加调试日志
  console.log('checkInNow - appointment对象:', appointment);
  console.log('staffId:', appointment.staffId);
  console.log('clnicId:', appointment.clnicId);

  // 检查是否有必需的字段
  if (!appointment.clnicId) {
    uni.showToast({
      title: '缺少坐诊信息，无法到诊',
      icon: 'error'
    });
    return;
  }

  if (!appointment.staffId) {
    uni.showToast({
      title: '缺少医生信息，无法到诊',
      icon: 'error'
    });
    return;
  }

  (uni as any).showModal({
    title: '确认到诊',
    content: `确认${appointment.doctorName}的预约已到诊吗？`,
    success: async (res: any) => {
      if (res.confirm) {
        try {
          (uni as any).showLoading({
            title: '正在处理...'
          });

          // 调用真实的API
          const requestParams: PutQueueRequest = {
            id: appointment.id,
            clnicId: appointment.clnicId!,
            staffId: appointment.staffId!,
            slotNo: appointment.slotNo!
          };

          console.log('发送到后端的完整参数:', requestParams);
          
          const response = await putQueue(requestParams);
          
          (uni as any).hideLoading();

          // 处理响应
          if (response.code === 200) {
            uni.showToast({
              title: '到诊成功',
              icon: 'success',
              duration: 2000
            });
            
            console.log('到诊成功响应:', response);
            
            // 刷新预约列表
            await fetchAppointments();
          } else {
            uni.showToast({
              title: response.msg || '到诊失败',
              icon: 'error'
            });
          }
        } catch (error) {
          (uni as any).hideLoading();
          console.error('到诊请求失败:', error);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'error'
          });
        }
      }
    }
  });
};
onLoad(() => {
  console.log("挂号记录页面 onLoad");
});

onMounted(() => {
  // 页面加载时获取挂号记录
  
  fetchAppointments();
});
</script>

<style lang="scss">
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.filter-section {
  background: white;
  border-bottom: 1rpx solid #eee;
}

.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #969799;
}

.error-section {
  padding: 100rpx 32rpx;
}

.appointment-list {
  padding: 16rpx;
}

.appointment-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  background: #f0f9ff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-actions {
  display: flex;
  gap: 16rpx;
}

.empty-state {
  padding: 100rpx 0;
}

.detail-popup {
  padding: 32rpx;
}

.detail-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 32rpx;
}

.detail-notes {
  margin-top: 16rpx;
}

/* 禁用状态的立即到诊按钮样式 */
.checkin-btn-disabled {
  background: #f5f5f5 !important;
  color: #c8c9cc !important;
  border: 1px solid #ebedf0 !important;
  box-shadow: none !important;
}

.checkin-btn-disabled .van-icon {
  margin-right: 8rpx;
  color: #c8c9cc !important;
}

.checkin-btn-disabled:active {
  transform: none !important;
}

/* 优化立即到诊按钮样式 */
.checkin-btn {
  background: linear-gradient(135deg, #07C160 0%, #00D4AA 100%) !important;
  border: none !important;
  box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3) !important;
  color: white !important;
  font-weight: bold !important;
}

.checkin-btn .van-icon {
  margin-right: 8rpx;
}

.checkin-btn:active {
  transform: scale(0.95);
  transition: transform 0.1s;
}

.checkin-btn::before {
  background: none !important;
}

.status-queuing {
  background-color: #1890ff !important;  // 自定义蓝色
  color: white !important;
}

// 或者使用渐变色
.status-queuing {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%) !important;
  color: white !important;
  border: none !important;
}
</style>